import sqlite3  
import os  
from coach.coach import Coach  

def get_history() -> 'dict':
    # 创建Coach实例并登录  
    instance = Coach()  
    instance.login()  
    # 获取用户历史记录  
    history : 'dict' = instance.fetch_user_history()  
    # print("历史记录：", history)  
    return history 

history = get_history()
database_path = os.path.join(os.path.dirname(__file__), '..', 'coach', 'database', 'coach.db')  
print("database file path", database_path)
conn = sqlite3.connect(database_path)  
cursor = conn.cursor()  

# 遍历列表中的每个记录，并将其插入到数据库中  
for record in history["list"]:  
    try:
        cursor.execute('''  
        INSERT INTO video_records (  
            title,  
            long_title,  
            cover,   
            uri,  
            oid,  -- history 字典的字段之一  
            bvid,  
            page, 
            cid,   
            author_name,  
            author_face,  
            author_mid,  
            view_at,  
            progress,  
            duration,  
            is_finish,  
            is_fav,  
            tag_name,  
            live_status  
        )  
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)  
        ''', (  
            record["title"],  
            record["long_title"],  
            record["cover"],  
            record["uri"],  
            record["history"]["oid"],  
            record["history"]["bvid"],  
            record["history"]["page"],  
            record["history"]["cid"],  
            record["author_name"],  
            record["author_face"],  
            record["author_mid"],  
            record["view_at"],  
            record["progress"],  
            record["duration"],  
            record["is_finish"],  
            record["is_fav"],  
            record["tag_name"],  
            record["live_status"]  
        ))
    except KeyError as e:  
        print(f"缺少必要的键: {e}, 跳过记录: {record}")  

conn.commit()  
cursor.close()  
conn.close()  
print("观看历史记录已保存到数据库中！")